package com.example.popupwindowtest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

public class TitleBarSelector{
	
	TextView showingView;
	private int windowFlag=-1;
	
	static ArrayList<String> hotKind=null;
	List<String> arealist1=new ArrayList<String>();
	List<String> kindlist1=new ArrayList<String>();
	static HashMap<String,List<String>> areaListMap = new HashMap<String,List<String>>();
	static HashMap<String,List<String>> kindListMap = new HashMap<String,List<String>>();
	HashMap<String, String> areaNumMap=new HashMap<String, String>();
	HashMap<String, String> kindNumMap=new HashMap<String, String>();
	HashMap<String, String> numHash=new HashMap<String, String>();
	Activity mthis;
	
	TextView areatab,kindtab,hottab;
	Drawable array1 , array2;
	View fatherView;
	PopupWindow window;
	LayoutInflater inflater;
	ListView listView1,listView2;
	Adapter adapter1,adapter2;
	SelectorResultInterface listener;
	private boolean isNeedNum;
	private boolean isNeedAreaSelect;//附近优惠券不需要区域筛选   这个参数设置
	
	
	public TitleBarSelector(Activity context,SelectorResultInterface listener){
		this(context,true,true,listener);
	}
	
	
	public TitleBarSelector(Activity context,boolean isNeedAreaSelect,boolean isNeedNum,SelectorResultInterface listener){
		
		mthis=context;
		this.listener=listener;
		this.isNeedNum=isNeedNum;
		this.isNeedAreaSelect=isNeedAreaSelect;
		mthis.findViewById(R.id.tabview).setVisibility(View.VISIBLE);
		initView();
		initData();
	}
	private void initView(){
		fatherView=mthis.findViewById(R.id.tabview);
		
		areatab=(TextView) mthis.findViewById(R.id.areatab);
		kindtab=(TextView) mthis.findViewById(R.id.kindtab);
		hottab=(TextView) mthis.findViewById(R.id.hottab);
		
		initTextBG();
		
		areatab.setOnClickListener(baseListener);
		kindtab.setOnClickListener(baseListener);
		hottab.setOnClickListener(baseListener);
		
		if(!isNeedAreaSelect){
			areatab.setVisibility(View.GONE);
		}
		
		WindowManager wm = (WindowManager) mthis.getSystemService(Context.WINDOW_SERVICE);
		Display display=wm.getDefaultDisplay();
		int width = display.getWidth();//屏幕宽度
		int height= display.getHeight();//屏幕宽度
		DisplayMetrics metrics = new DisplayMetrics();
		display.getMetrics(metrics);
		 
		inflater=(LayoutInflater) mthis.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v=inflater.inflate(R.layout.popup_windows, null, false);
		listView1=(ListView) v.findViewById(R.id.list1);
		listView2=(ListView) v.findViewById(R.id.list2);
		if (Build.VERSION.SDK_INT >= 9) {
			//
			Class[] args1 = new Class[1];
			args1[0]=int.class;
			try
			{
				Method m=View.class.getDeclaredMethod("setOverScrollMode",args1);
				m.setAccessible(false);
				Object o[]=new Object[1];
				o[0]=2;
				m.invoke(listView1, o);
				m.invoke(listView2, o);
			}
			catch (SecurityException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (NoSuchMethodException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IllegalArgumentException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IllegalAccessException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (InvocationTargetException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
		
		adapter1=new Adapter();
		listView1.setAdapter(adapter1);
		
		adapter2=new Adapter();
		listView2.setAdapter(adapter2);
		listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				adapter1.setSelect(position);
				TextView v=(TextView) view.findViewById(R.id.selecttex);
				String text=v.getText().toString();
				
				if(text.contains("全部")){
					showingView.setText(text);
					showingView.setTag(position);
					window.dismiss();
					if(listener!=null){
						String hottabtext=hottab.getText().toString();
						if(hottabtext.contains("最热门")){
							hottabtext="hot";
						}else if(hottabtext.contains("离我最近")){
							hottabtext="distance";
						}else if(hottabtext.contains("新发布")){
							hottabtext="new";
						}else if(hottabtext.contains("人均高到低")){
							hottabtext="averagespend"+"&ordertype=desc";
						}else if(hottabtext.contains("人均低到高")){
							hottabtext="averagespend"+"&ordertype=asc";
						}
						
						listener.successed(areatab.getText().toString(),kindtab.getText().toString(),hottabtext);
					}
					return;
				}
				
				switch(showingView.getId()){
					case R.id.areatab:
						adapter2.setList(areaListMap.get( adapter1.getItem(adapter1.getSelect())));
						break;
					case R.id.kindtab:
						adapter2.setList(kindListMap.get( adapter1.getItem(adapter1.getSelect())));
						break;
				}
				
				adapter1.notifyDataSetChanged();
				adapter2.notifyDataSetChanged();
			}
		});
		
		listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				String value= (String) adapter2.getItem(position);
				if(value.contains("全部")){
					showingView.setText( adapter1.getItem(adapter1.getSelect()).toString());
				}else{
					showingView.setText(value);
				}
				
				showingView.setTag(adapter1.getSelect());
				
				if(listener!=null){
					String hottabtext=hottab.getText().toString();
					if(hottabtext.contains("最热门")){
						hottabtext="hot";
					}else if(hottabtext.contains("离我最近")){
						hottabtext="distance";
					}else if(hottabtext.contains("新发布")){
						hottabtext="new";
					}else if(hottabtext.contains("人均高到低")){
						hottabtext="averagespend"+"&ordertype=desc";
					}else if(hottabtext.contains("人均低到高")){
						hottabtext="averagespend"+"&ordertype=asc";
					}
					
					listener.successed(areatab.getText().toString(),kindtab.getText().toString(),hottabtext);
				}
				window.dismiss();
			}
		});
		
		
		int[] xy=new int[2];
		fatherView.getLocationOnScreen(xy);
//		window=new PopupWindow(v,width,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 320, metrics));
		window=new PopupWindow(v);
		window.setTouchable(true);
		window.setFocusable(true);
		window.setOutsideTouchable(false);
		window.setOnDismissListener(dismissListener);
		window.setBackgroundDrawable(new BitmapDrawable());
		window.setAnimationStyle(R.style.listwindowanimation);
		
	}
	
	private void initTextBG(){
		if (isNeedAreaSelect)
		{
			areatab.setBackgroundResource(R.drawable.filter_bg3);
			kindtab.setBackgroundResource(R.drawable.filter_bg3);
			hottab.setBackgroundResource(R.drawable.filter_bg3);
		}else{
			areatab.setBackgroundResource(R.drawable.filter_bg2);
			kindtab.setBackgroundResource(R.drawable.filter_bg2);
			hottab.setBackgroundResource(R.drawable.filter_bg2);
		}
		
	}
	
	private void initData(){
		
		String hotliststring[] ={"最热门","新发布","人均低到高","人均高到低"};
		
		hotKind=new ArrayList<String>();
		if (!isNeedAreaSelect)
		{
			hotKind.add("离我最近");
		}
		for (int i = 0; i < hotliststring.length; i++)
		{
			hotKind.add(hotliststring[i]);
		}
		hottab.setText(hotKind.get(0));
		
		
		//区域划分
		for(int a='A';a<'K';a++){
			ArrayList<String> list=new ArrayList<String>();
			String key=((char)a)+"";
			arealist1.add(key);
			
			for(int i=10;i>=0;i--){
				list.add(key+i);
			}
			areaListMap.put(key, list);
		}
		
		
		//区域划分
				for(int a='E';a<'M';a++){
					ArrayList<String> list=new ArrayList<String>();
					String key=((char)a)+"";
					kindlist1.add(key);
					
					for(int i=10;i>=0;i--){
						list.add(key+i);
					}
					kindListMap.put(key, list);
				}
		
	}
	
	/**
	 * 
	 * @param area
	 * @param kind
	 * @param hot
	 */
	public void setValues(String area,String kind,String hot){
		if(area!=null&&!"".equals(area)){
			int index=arealist1.indexOf(area);
			if(index>=0){
				areatab.setTag(index);
				areatab.setText(area);
			}else{
				int a=arealist1.size();
				for (int i=0;i<a;i++)
				{
					String fatherArea=arealist1.get(i);
					List<String> list= areaListMap.get(fatherArea);
					if(list.contains(area)){
						areatab.setTag(i);
						areatab.setText(area);
						break;
					}
				}
			}
		}
		
		if(kind!=null&&!"".equals(kind)){
			int index=kindlist1.indexOf(kind);
			if(index>=0){
				kindtab.setTag(index);
				kindtab.setText(kind);
			}else{
				int a=kindlist1.size();
				for (int i=0;i<a;i++)
				{
					String fatherArea=kindlist1.get(i);
					List<String> list= kindListMap.get(fatherArea);
					if(list.contains(kind)){
						kindtab.setTag(i);
						kindtab.setText(kind);
						break;
					}
				}
			}
			
			
		}
		
		if(hot!=null&&!"".equals(hot)){
			if(hotKind.contains(hot)){
				hottab.setText(hot);
			}
			
		}
		
	}
	
	
	
	OnDismissListener dismissListener=new OnDismissListener()
	{
		
		@Override
		public void onDismiss()
		{
			if(isNeedAreaSelect){
				showingView.setBackgroundResource(R.drawable.filter_bg3);
			}else{
				showingView.setBackgroundResource(R.drawable.filter_bg2);
			}
		}
	};
	
	OnClickListener baseListener=new OnClickListener()
	{
		
		@Override
		public void onClick(View v)
		{
			int select=0;
			TextView tab=(TextView) v;
			try
			{
				adapter2.setSelect(-1);
				select=Integer.parseInt(tab.getTag().toString());
				adapter1.setSelect(select);
				
			}
			catch (NumberFormatException e)
			{
				e.printStackTrace();
			}
			showingView=tab;
			String nowValue=tab.getText().toString();
			
			if(isNeedAreaSelect){
				tab.setBackgroundResource(R.drawable.filter_bg3ed);
			}else{
				tab.setBackgroundResource(R.drawable.filter_bg2ed);
			}
			
			listView1.setVisibility(View.VISIBLE);
			switch (v.getId()){
				case R.id.areatab:
					adapter1.setList(arealist1);
					adapter2.setList(areaListMap.get( adapter1.getItem(adapter1.getSelect())));
					numHash=areaNumMap;
					break;
				case R.id.kindtab:
					adapter1.setList(kindlist1);
					adapter2.setList(kindListMap.get( adapter1.getItem(adapter1.getSelect())));
					numHash=kindNumMap;
					break;
				case R.id.hottab:
					listView1.setVisibility(View.GONE);
					adapter2.setList(hotKind);
					adapter2.setSelect(hotKind.indexOf(tab.getText().toString()));
					break;
							
			}
			
			adapter1.notifyDataSetChanged();
			adapter2.notifyDataSetChanged();
			
			listView1.setSelection(select);
			
			showWindow(v);
		}
	};
	
	
	
	public void showWindow(View v){
		WindowManager wm = (WindowManager) mthis.getSystemService(Context.WINDOW_SERVICE);
		Display display=wm.getDefaultDisplay();
		int width = display.getWidth();//屏幕宽度
		int height= display.getHeight();//屏幕宽度
		int[] a=new int[2];
		v.getLocationOnScreen(a);
		window.setWidth(width);
		window.setHeight(height-a[1]+v.getHeight());
		
		if(!window.isShowing()){
			window.showAsDropDown(fatherView);
		}
	}
	
	
	class Adapter extends BaseAdapter{
		List<String> list=new ArrayList<String>();;
		
		private int select=0;
		private boolean selectAble=false;
		
		public int getSelect() {
			return select;
		}
		public void setSelect(int select) {
			this.select = select;
			selectAble=true;
		}

		public List<String> getList() {
			return list;
		}

		public void setList(List<String> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			if(convertView==null){
				LayoutInflater in=(LayoutInflater) mthis.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				convertView=in.inflate(R.layout.popwindowitem, null);
			}
			
			TextView text=(TextView) convertView.findViewById(R.id.selecttex);
			
			TextView num=(TextView) convertView.findViewById(R.id.selectnum);
			
			String value=list.get(position);
			text.setText(value);
			
			String numtext=numHash.get(value);
			if(numtext!=null){
				num.setVisibility(View.VISIBLE);
				num.setText(numtext);
			}else{
				
				if(value.equals("全部")){
					numtext=numHash.get(adapter1.getItem(adapter1.select));
					num.setVisibility(View.VISIBLE);
					num.setText(numtext);
				}else{
					num.setVisibility(View.GONE);
				}
				
			}
			
			if(select==position&&selectAble){
				convertView.setBackgroundResource(R.drawable.filiter_bg_1_ch);
			}else{
				convertView.setBackgroundResource(android.R.color.transparent);
			}
			return convertView;
		}
		
	}
	
	
}